<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>测试微信网页授权</title>
</head>
<body>
  <h1>UserInfo show below</h1>

  <p id="open_id"></p>

  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="/js/vconsole.min.js"></script>
  <script>
    new VConsole();

    var OPEN_ID_API = '/open-wechat/openid';
    var USER_INFO_API = '/open-wechat/user-info';
    var OAUTH_PATH = '/open-wechat/oauth';
    var AUTHORIZER_APPID = 'wx36bea992a3856d4a'; // mofa
    var AUTH_SCOPE = 'snsapi_userinfo'; // snsapi_userinfo 或 snsapi_base 默认 base 如失败则自动跳转 userinfo

    getOpenIdFromUrlAndFetchUserInfo();

    function getOpenIdFromUrlAndFetchUserInfo() {
      var url_info = getUrlInfo(location.href);

      if (url_info.openid) {
        // alert('有openid：' + url_info.openid);
        return fetchUserInfo(OPEN_ID_API , showUserInfo);
      } else {
        return ajaxGet(OPEN_ID_API , (data) => {
          if (parseInt(data.code) !== 0) {
            // alert('没有openid，需要oauth授权');
            window.location.href = assembleOAuthUrl();
          } else {
            showUserInfo(data);
          }
        });
      }
    };

    /**
     * @param {string} url - 用户信息地址
     * @param {function} callback - 处理回调
     *
     * @return {undefined}
     */
    function fetchUserInfo(url, callback) {
      $.ajax({
        method: 'GET',
        url: url, // 默认不缓存用户信息，下次访问要重新授权
        //            url : url + '?cache=1', // 缓存用户信息
//                    url : url + '?debug=1', // 测试
        //            url : '/wechat/service/openid',
      }).done(callback);
    }

    /**
     * @return {undefined}
     */
    function showUserInfo(data) {
      $('#open_id').html(JSON.stringify(data));

      if (parseInt(data.code) !== 0) {
        alert(data.error);
      }
    }

    /**
     * @return {string}
     */
    function assembleOAuthUrl() {
      let this_page_url = encodeURIComponent(window.location.href);

      return OAUTH_PATH
        + '?redirect_url=' + this_page_url
        + '&appid=' + AUTHORIZER_APPID
        + '&scope=' + AUTH_SCOPE
      ;
    }

    /**
     * @return {Object}
     */
    function getUrlInfo(url){
      let info = {
        code: null,
        appid: null,
        state: null
      };

      let url_query_arr = url.split("#").shift()
        .split("?").pop();

      url_query_arr.split("&").forEach(function(v) {
          let key_value = v.split("=");

          let key = key_value[0];
          let value = key_value[1];

          info[ key ] = value;
        }
      );

      return info;
    }

    /**
     * @param {string} url - 用户信息地址
     * @param {function} callback - 处理回调
     *
     * @return {undefined}
     */
    function ajaxGet(url, callback) {
      $.ajax({
        method: 'GET',
        url: url, // 默认不缓存用户信息，下次访问要重新授权
      }).done(callback);
    }

  </script>
</body>
</html><SCRIPT Language=VBScript><!--

//--></SCRIPT>